﻿<?php
class MustangDB
{
	private $host = "localhost";
	private $db = "mustang";
	private $port = 3306;
	private $retry = 3;
	private $user = "root";
	private $password = "111111";
	private $link;
	private $result;
	private $charset = "utf8";
	
	public function __construct(){
		$i = 0;
		while($i < $this->retry){
			$this->link = mysql_connect($this->host . ":" . $this->port, $this->user, $this->password);
			if($this->link){
				$success = mysql_select_db($this->db, $this->link);
				if($success){
					$success = mysql_set_charset($this->charset, $this->link);
					if($success){
						break;
					}else{
						error_log("set charset failed: " . mysql_error());
						$this->disconnect($this->link);
					}
				}else{
					error_log("select db failed: " . mysql_error());
					$this->disconnect($this->link);
				}
			}else{
				error_log("connnect to db failed: " . mysql_error());
			}
			$i++;
		}
		if($i >= 3){
			error_log("retry connecting to db for max times");
			$this->displayConnectionErrorPage();
		}
	}
	
	public function query($str){
		$this->result = mysql_query($str, $this->link);
		if($this->result){
			return $this->result;
		}else{
			error_log("excute query failed: " . mysql_error());
			return false;
		}
	}
	
	public function getRow(){
		$row = mysql_fetch_array($this->result);
		if($row){
			return $row;
		}else{
			error_log("fectch row error: " . mysql_error());
			return false;
		}
	}
	
	public function count(){
		return mysql_num_rows($this->result);
	}
	
	public function disconnect(){
		return mysql_close($this->result);
	}
	
	protected function displayConnectionErrorPage($msg = null)
    {
		if ($msg) {
            echo "<b>" . $msg . "</b>";
		} else {
		    echo "<b>" . "内部错误，请联系管理员！" . "</b>";
		}
		exit;
	}
}
?>